package com.sky.service.impl.admin;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.BaseException;
import com.sky.mapper.user.OrderDetailMapper;
import com.sky.mapper.user.OrderMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.OrderService;
import com.sky.utils.BaiDuMapUtil;
import com.sky.vo.OrderStatisticsVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.Alias;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service("adminOrderServiceImpl")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public Result<PageResult> getOrderPageInfo(OrdersPageQueryDTO dto) {

        // todo： 使用 Spring task 优化
////   收集超时数据id，若是待付款商品,该商品订单时间过去15分钟后,将其订单状态更改为已取消
//        List<Long> outTimeOrderIds = new ArrayList<>();
//        ordersList.forEach(e -> {
//            if (e.getStatus().equals(Orders.PENDING_PAYMENT)) {
//                // 下单时间
//                LocalDateTime orderTime = e.getOrderTime();
//                // 支付超时时间
//                LocalDateTime outTime = orderTime.plusMinutes(15);
//                // 查看历史记录时间
//                LocalDateTime now = LocalDateTime.now();
//                if (now.isAfter(outTime)) outTimeOrderIds.add(e.getId());
//            }
//        });
//
////     更新数据 该商品订单时间过去15分钟后,将其订单状态更改为已取消
//        if (!outTimeOrderIds.isEmpty()) orderMapper.setOrderSatatusToCancelByIds(outTimeOrderIds);

        List<Orders> ordersList = orderMapper.getOrderPageInfo(dto);
        // 获取处理后的最新分页数据
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);

        // 封装结果集
        PageResult result = new PageResult(pageInfo.getTotal(), pageInfo.getList());

        return Result.success(result);
    }


    @Override
    public Result<Orders> getOrderDetailById(Long id) {
        Orders orders = orderMapper.selectById(id);

        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrder(orders);

        orders.setOrderDetails(orderDetailList);

        return Result.success(orders);
    }

    @Override
    public Result<OrderStatisticsVO> getOrderStatusCount() {
//        订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setConfirmed(orderMapper.getOrderStatusCount(Orders.CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.getOrderStatusCount(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.getOrderStatusCount(Orders.DELIVERY_IN_PROGRESS));

        return Result.success(orderStatisticsVO);
    }


    @Override
    @Transactional
    public Result<Object> confirmOrderById(OrdersConfirmDTO dto) {
        if (dto == null) throw new BaseException("关键数据不合法,请检查参数");

        dto.setStatus(Orders.CONFIRMED);

        Orders orders = new Orders();

        BeanUtils.copyProperties(dto, orders);

        orderMapper.update(orders);

        return Result.success();

    }

    @Override
    @Transactional
    public Result<Object> rejectionOrder(OrdersRejectionDTO dto) {
        // todo 这里应该需要调用微信的退款接口 后续业务扩充 回来更改
        if (dto == null) throw new BaseException("关键数据不不合法,请检查参数");

        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);

        orders.setStatus(Orders.CANCELLED);

        orderMapper.update(orders);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<Object> deliveryOrders(Long id) {
        if (id == null) throw new BaseException("关键数据不不合法,请检查参数");

        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<Object> cancelOrder(OrdersCancelDTO dto) {
        // todo 该接口实现未涉及微信退款  有需求再回来改
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);

        return Result.success();

    }


    @Override
    @Transactional
    public Result<Object> completeOrders(Long id) {
        if (id == null) throw new BaseException("关键数据不不合法,请检查参数");

        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);

        orderMapper.update(orders);

        return Result.success();
    }

}
